﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

using TathamOddie.OpenSearchValidator.Logic;

namespace TathamOddie.OpenSearchValidator.WebUI
{
	public partial class Validate : System.Web.UI.Page
	{
		protected Message[] Messages { get; set; }

		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);

			var pageAddress = Request.QueryString["p"];
			var searchTerms = Request.QueryString["st"];

			var pageUri = TryParseUri(pageAddress);

			if (pageUri == null)
			{
				Response.Redirect("~/");
				return;
			}

			var validator = new Validator();
			var messages = validator.Validate(pageUri, searchTerms);

			Messages = messages;

            SetFavIcon(messages);

			DataBind();
		}

		private Uri TryParseUri(string address)
		{
			if (string.IsNullOrEmpty(address))
			{
				return null;
			}

			if (!address.StartsWith("http", StringComparison.OrdinalIgnoreCase))
			{
				address = "http://" + address;
			}

			try
			{
				return new Uri(address, UriKind.Absolute);
			}
			catch (FormatException)
			{
				return null;
			}
		}

		protected Message GetMessage(RepeaterItem container)
		{
			return (Message)container.DataItem;
		}

		protected string GetResultCssClass(Message message)
		{
			return message.Type.ToString().ToLowerInvariant();
		}

        void SetFavIcon(IEnumerable<Message> messages)
        {
            var image = "data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%10%00%00%00%10%08%02%00%00%00%90%91h6%00%00%00%19IDAT(%91c%0C%DD%10%C5%40%0A%60%22I%F5%A8%86Q%0DCJ%03%00dy%01%7F%0C%9F0%7D%00%00%00%00IEND%AEB%60%82";
            if (messages.Any(m => m.Type == MessageType.Warning))
            {
                image = "data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%10%00%00%00%10%08%03%00%00%00%28-%0FS%00%00%00%19tEXtSoftware%00Adobe%20ImageReadyq%C9e%3C%00%00%00%06PLTE%EE%DD%00%00%00%00%F8Lx%D5%00%00%00%0FIDATx%DAb%60%18%05%C8%00%20%C0%00%01%10%00%01%3BBBK%00%00%00%00IEND%AEB%60%82";
            }
            if (messages.Any(m => m.Type == MessageType.Failure))
            {
                image = "data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%10%00%00%00%10%08%02%00%00%00%90%91h6%00%00%00%19IDAT(%91c%BCd%AB%C2%40%0A%60%22I%F5%A8%86Q%0DCJ%03%00%DE%B5%01S%07%88%8FG%00%00%00%00IEND%AEB%60%82";
            }

            var link = new HtmlLink();
            link.Attributes.Add("rel", "icon");
            link.Attributes.Add("type", "image/png");
            link.Attributes.Add("href", image);
            Header.Controls.Add(link);
        }
	}
}